// import { Notification, MessageBox, Message, ElLoading } from 'element-ui'
import {
  ElNotification,
  ElMessageBox,
  ElMessage,
  ElLoading,
} from "element-plus";
import store from "@/store";
import { generateSignature } from "./signatureUtils"; // 引入签名生成方法
import { getToken } from "./auth";
import errorCode from "./errorCode";
import { tansParams, blobValidate } from "./ruoyi";
import cache from "@/plugins/cache";
import { saveAs } from "file-saver";
import { debounce } from "./index";
import router from "@/router";

const appId = "HCIT";
const secretKey = "HCIT@{2024}@";
const restfulToken = "83183546-6fbb-4afe-936a-45df3b56aa88"; // restful令牌

export let isRelogin = { show: false };

// 生成提示的节流函数
let errorMsg = debounce(
  (msg) => {
    ElMessage.error(msg);
  },
  window.HC_config.VUE_ERROR_MESSAGE_DURATION || 1000,
  false
);

let requestLoading;

export function closeLoading() {
  if (requestLoading) {
    requestLoading.close();
  }
}

export async function requestBefore(config) {
  // ------进入请求前拦截函数-------

  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
  delete config.headers.repeatSubmit; //移除请求头中的属性。避免被后端拦截
  if (getToken() && !isToken) {
    config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  //将用户选择的机构设置放入请求头中
  if (store.state.user.currentOrgUnid) {
    config.headers["X-TOKEN"] = store.state.user.currentOrgUnid;
  }

  if (window.HC_config.VUE_APP_REQUEST_SIGNATURE) {
    // 在每个请求发起之前生成签名
    const { signature } = await generateSignature(
      restfulToken,
      appId,
      secretKey
    );

    // 动态设置请求头
    config.headers["X-Signature"] = signature;
  }

  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }

  if (config.method === "post" && !config.noLoading) {
    //开启loading
    if (config.responseType == "blob") {
      requestLoading = ElLoading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    } else {
      requestLoading = ElLoading.service({
        text: "",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }
  }

  if (
    !isRepeatSubmit &&
    (config.method === "post" || config.method === "put")
  ) {
    const requestObj = {
      url: config.url,
      data:
        typeof config.data === "object"
          ? JSON.stringify(config.data)
          : config.data,
      time: new Date().getTime(),
    };
    const sessionObj = cache.session.getJSON("sessionObj");
    if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
      cache.session.setJSON("sessionObj", requestObj);
    } else {
      const s_url = sessionObj.url; // 请求地址
      const s_data = sessionObj.data; // 请求数据
      const s_time = sessionObj.time; // 请求时间
      const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
      if (
        s_data === requestObj.data &&
        requestObj.time - s_time < interval &&
        s_url === requestObj.url
      ) {
        const message = "数据正在处理，请勿重复提交";
        requestLoading && requestLoading.close();
        console.warn(`[${s_url}]: ` + message);
        return Promise.reject(new Error(message));
      } else {
        cache.session.setJSON("sessionObj", requestObj);
      }
    }
  }
  return config;
}

export function requestAfter(res) {
  // ------进入请求后拦截函数-------
  let config = res.config;
  if (config.method == "post") {
    requestLoading && requestLoading.close();
  }
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200;
  // 获取错误信息
  // if(res.data.message)
  let msg;
  //检验是否有中文
  msg =
    errorCode[code] || res.data.message || res.data.msg || errorCode["default"];
  // 二进制数据则直接返回
  if (
    res.request.responseType === "blob" ||
    res.request.responseType === "arraybuffer"
  ) {
    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    try {
      if (
        res.headers.get("content-disposition") &&
        filenameRegex.exec(res.headers.get("content-disposition"))
      ) {
        let fieldName = decodeURI(
          filenameRegex.exec(res.headers.get("content-disposition"))[1]
        );
        return {
          fieldName: fieldName,
          data: res.data,
        };
      } else {
        return res.data;
      }
    } catch (error) {
      return res.data;
    }
  }
  if (code === 401 || code === 403) {
    if (!isRelogin.show) {
      isRelogin.show = true;
      ElMessageBox.confirm(
        "登录状态已过期，您可以继续留在该页面，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          isRelogin.show = false;
          store.dispatch("user/LogOut").then(() => {
            if (window.HC_config.VUE_APP_LOGIN_URL == "ssLogin") {
              location.href = "login";
            } else {
              location.href = location.href;
            }
          });
        })
        .catch(() => {
          isRelogin.show = false;
        });
    }
    return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
  } else if (code === 500) {
    if (!config.noShowError) {
      errorMsg(msg);
    }
    return Promise.reject(res);
  } else if (code !== 200) {
    if (!config.noShowError) {
      errorMsg(msg);
    }
    return Promise.reject(res);
  } else {
    return res.data;
  }
}

let downloadLoadingInstance;
// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return service
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
    .then(async (data) => {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        ElMessage.error(errMsg, null, null, { url: url });
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      ElMessage.error("下载文件出现错误，请联系管理员！", null, null, {
        backErrorUrl: url,
      });
      downloadLoadingInstance.close();
    });
}

// 通用下载方法
export function downloadBlob(url) {
  downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return new Promise((resolve, reject) => {
    fetch(url, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
      .then((P_Response) => {
        // 确保响应是 OK 的
        if (!P_Response.ok) {
          reject("Network response was not ok.");
          return;
        }
        // 返回 Blob 对象
        return P_Response.blob().then((P_Blob) => {
          // 如果需要，创建一个新的 Blob 对象，这次明确指定其类型
          return new Blob([P_Blob]);
        });
      })
      .then((blob) => {
        resolve(blob);
      })
      .catch((r) => {
        console.error(r);
        ElMessage.error("下载文件出现错误，请联系管理员！", null, null, {
          url: url,
        });
        reject(r);
      })
      .finally(() => {
        downloadLoadingInstance.close();
      });
  });
}
